#!/usr/bin/ruby
# file: server.rb

require 'sqlite3'
require "webrick"
require "xmlrpc/server"

db = SQLite3::Database.new("chat.db")

s = XMLRPC::WEBrickServlet.new
s.add_handler("Chat.SendMessage") do |sender, msg|
	puts "Received (" + sender + "): " + msg
	db.execute("insert into message values (null, ?, ?)", sender, msg.strip)
	true #return true
end

s.add_handler("Chat.GetMessage") do |id|
	maxid = db.get_first_row("select ifnull(max(id),0) from message")
	row = db.get_first_row("select sender, message from message where id = ?", id)
	if row == nil
		""
	else
		maxid[0] + ";" + row.join(";")
	end
end

#kalo client request fungsi yang gaa ada
s.set_default_handler do |name, *args|
  raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
                                   " or wrong number of parameters!")
end

httpserver = WEBrick::HTTPServer.new(:Port => 8000)
httpserver.mount("/rpc", s)
trap("INT") { httpserver.shutdown }   #buat tangkep signal ctrl+c -> matiin server
httpserver.start
